package main

import (
	"bytes"
	"fmt"
	"io"
	"os"
	"os/exec"
	"path"

	"github.com/gin-gonic/gin"
)

const (
	SavePath = "D:/4444"
)

func ActionListTasks(c *gin.Context) {
	fmt.Println("run 查询系统线程")
	c.JSON(200, gin.H{"status": "run 查询系统线程"})
}

func ActionStartBaiduyun(c *gin.Context) {
	fmt.Println("run 打开百度云")
	c.JSON(200, gin.H{"status": "run 打开百度云"})
}

func ActionStopBaiduyun(c *gin.Context) {
	fmt.Println("run 关闭百度云")
	c.JSON(200, gin.H{"status": "run 关闭百度云"})
}

func ActionScreenCut(c *gin.Context) {
	fmt.Println("run 显示电脑屏幕")
	c.JSON(200, gin.H{"status": "run 显示电脑屏幕"})
}

func copy(src, dst string) (int64, error) {
	sourceFileStat, err := os.Stat(src)
	if err != nil {
		return 0, err
	}

	if !sourceFileStat.Mode().IsRegular() {
		return 0, fmt.Errorf("%s is not a regular file", src)
	}

	source, err := os.Open(src)
	if err != nil {
		return 0, err
	}
	defer source.Close()

	destination, err := os.Create(dst)
	if err != nil {
		return 0, err
	}
	defer destination.Close()
	nBytes, err := io.Copy(destination, source)
	return nBytes, err
}

func ActionSaveFile(c *gin.Context) {
	filePath := c.Query("path")
	targetPath := path.Join(SavePath, path.Base(filePath))
	copy(filePath, targetPath)
	msg := fmt.Sprintf("保存成功 from %s, %s\n", filePath, targetPath)
	c.JSON(200, gin.H{"status": msg})
}

func ActionShutdown(c *gin.Context) {
	//函数返回一个*Cmd，用于使用给出的参数执行name指定的程序
	cmd := exec.Command("shutdown", "-s", "-t", "20")

	//读取io.Writer类型的cmd.Stdout，再通过bytes.Buffer(缓冲byte类型的缓冲器)将byte类型转化为string类型(out.String():这是bytes类型提供的接口)
	var out bytes.Buffer
	cmd.Stdout = &out

	//Run执行c包含的命令，并阻塞直到完成。  这里stdout被取出，cmd.Wait()无法正确获取stdin,stdout,stderr，则阻塞在那了
	cmd.Run()
	c.JSON(200, gin.H{"status": "成功"})
}

func BuildCommandMapping(engine *gin.Engine) {
	commandList := engine.Group("/command")
	commandList.GET("/taskList", ActionListTasks)
	commandList.GET("/baiDuYunStart", ActionStartBaiduyun)
	commandList.GET("/baiDuYunStop", ActionStopBaiduyun)
	commandList.GET("/screenCut", ActionScreenCut)
	commandList.GET("/saveFile", ActionSaveFile)
	commandList.GET("/shutdown", ActionShutdown)
}
